﻿using EnglishStudy.Entity;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Input;
using Microsoft.Phone.Shell;
using System.Windows.Controls;

namespace EnglishStudy.ViewModel
{
    class StudyViewModel : INotifyPropertyChanged
    {
        private LessonDataContext lessonDB;

        // Class constructor, create the data context object.
        public StudyViewModel(string lessonDBConnectionString)
        {
            lessonDB = new LessonDataContext(lessonDBConnectionString);
            // Specify the query for all to-do items in the database.
            ////var newWord = from WordTable item in lessonDB.WordList
            ////              where item.Frequency == 1
            ////              select item;

            ////// Query the database and load all to-do items.
            ////NewWordList = new ObservableCollection<WordTable>(newWord);
        }

        // A list of all new word
        private ObservableCollection<WordTable> _newWordList;
        public ObservableCollection<WordTable> NewWordList
        {
            get { return _newWordList; }
            set
            {
                _newWordList = value;
                NotifyPropertyChanged("NewWordList");
            }
        }

        // A list of all miss pronounced word
        private ObservableCollection<WordTable> _missPronouncedWordList;
        public ObservableCollection<WordTable> MissPronouncedWordList
        {
            get { return _missPronouncedWordList; }
            set
            {
                _missPronouncedWordList = value;
                NotifyPropertyChanged("MissPronouncedWordList");
            }
        }


        // Query database and load the word list.
        public void LoadCollectionsFromDatabase()
        {

        }

 

        // return true if a word is in top 2000 common word list
        public WordTable isCommonWord(string word)
        {
            List<WordTable> commonWord = (from WordTable wordItem in lessonDB.WordList
                                          where (wordItem.Word == word && wordItem.IsLearned == false)
                                          select wordItem).ToList();
            if (commonWord != null && commonWord.Count > 0)
                return commonWord[0];
            else
                return null;
        }

        // Write changes in the data context to the database.
        public void SaveChangesToDB()
        {
            lessonDB.SubmitChanges();
        }

        // return a list of word that is in common word
        public ObservableCollection<WordTable> getNewWords(string inputString)
        {
            Regex pattern = new Regex(@"[^a-zA-Z0-9\s']");
            inputString = inputString.Replace('\n', ' ');
            inputString = pattern.Replace(inputString.ToLower(), "");
            inputString = RemoveDuplicateWords(inputString);
            List<string> lstrings = inputString.Split(' ').ToList();

            var commonWord = (from WordTable wordItem in lessonDB.WordList
                              where lstrings.Contains(wordItem.Word) && wordItem.IsLearned == false
                              select wordItem);
            ObservableCollection<WordTable> commonWordCollection = new ObservableCollection<WordTable>(commonWord);
            if (commonWordCollection != null && commonWordCollection.Count > 0)
                return commonWordCollection;
            else
                return null;
        }

        private string RemoveDuplicateWords(string v)
        {
            // 1
            // Keep track of words found in this Dictionary.
            var d = new Dictionary<string, bool>();

            // 2
            // Build up string into this StringBuilder.
            StringBuilder b = new StringBuilder();

            // 3
            // Split the input and handle spaces and punctuation.
            string[] a = v.Split(new char[] { ' ', ',', ';', '.' },
                StringSplitOptions.RemoveEmptyEntries);

            // 4
            // Loop over each word
            foreach (string current in a)
            {
                // 5
                // Lowercase each word
                string lower = current.ToLower();

                // 6
                // If we haven't already encountered the word,
                // append it to the result.
                if (!d.ContainsKey(lower))
                {
                    b.Append(current).Append(' ');
                    d.Add(lower, true);
                }
            }
            // 7
            // Return the duplicate words removed
            return b.ToString().Trim();
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify Silverlight that a property has changed.
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        #region Icommand
        public ICommand ItemSelectedCommand
        {
            get
            {
                return new DelegateCommand(ItemSelected, CanExcute);
            }
        }

        private void ItemSelected(object parameter)
        {
            var list = parameter as ListBox;
            if (list.SelectedItem == null)
                return;
            PhoneApplicationService.Current.State["Word"] = list.SelectedItem as WordTable;
            list.SelectedItem = null;
        }

        public bool CanExcute(object obj)
        {
            return true;
        }

        public ICommand ItemSelectedCommand1
        {
            get
            {
                return new DelegateCommand(ItemSelected, CanExcute);
            }
        }
        //ItemSelectedCommand1
        #endregion
    }
}
